import { useState, useEffect } from 'react'
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Select,
  DatePicker,
  Table,
  Image,
  Tag,
  Space,
  Modal,
  message
} from 'antd'
import {
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons'
import { Link } from 'react-router-dom'
import 'moment/locale/zh-cn'
import locale from 'antd/es/date-picker/locale/zh_CN'
import { useDispatch, useSelector } from 'react-redux'
import { useNavigate } from 'react-router-dom'
import {
  getChannels,
  getArticleList,
  delArticle
} from '@/store/actionCreators/article'
import defaultImg from '@/assets/defaultImg.png'

const { Option } = Select
const { RangePicker } = DatePicker
const { confirm } = Modal

const Article = () => {
  const STATUS = [
    { id: -1, title: '全部', color: 'magenta' },
    { id: 0, title: '草稿', color: 'red' },
    { id: 1, title: '待审核', color: 'volcano' },
    { id: 2, title: '审核通过', color: 'lime' },
    { id: 3, title: '审核失败', color: 'gold' }
  ]

  const dispatch = useDispatch()
  const navigate = useNavigate()

  // 获取频道列表
  useEffect(() => {
    dispatch(getChannels())
  }, [dispatch])

  const [query, setQuery] = useState({
    status: null,
    channel_id: null,
    begin_pubdate: null,
    end_pubdate: null,
    page: 1,
    per_page: 10
  })
  // 获取文章列表
  useEffect(() => {
    dispatch(getArticleList(query))
  }, [dispatch, query])

  // 频道数据、文章列表数据、总条数
  const { channels, list, total_count } = useSelector(state => state.article)

  // 状态、频道、日期选中设置
  const [status, setStatus] = useState(null)
  const [channel, setChannel] = useState(null)
  const [date, setDate] = useState(null)

  // 删除文章
  const del = id => {
    confirm({
      title: '提示',
      icon: <ExclamationCircleOutlined />,
      content: '确认删除吗?',
      onOk: async () => {
        // 删除
        await dispatch(delArticle(id))

        // 提示
        message.success('删除成功~')

        // 重新查询
        setQuery({ ...query })
      },
      onCancel () {
        console.log('Cancel')
      }
    })
  }

  // 表格列的定义
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render: cover => (
        <Image
          alt=''
          style={{ width: 200, height: 100 }}
          src={cover.images[0]}
          fallback={defaultImg}
        />
      )
    },
    {
      title: '标题',
      dataIndex: 'title'
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: status => {
        const statusObj = STATUS.find(item => item.id === status)

        return <Tag color={statusObj.color}>{statusObj.title}</Tag>
      }
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate'
    },
    {
      title: '阅读数',
      dataIndex: 'read_count'
    },
    {
      title: '评论数',
      dataIndex: 'comment_count'
    },
    {
      title: '点赞数',
      dataIndex: 'like_count'
    },
    {
      title: '操作',
      render: (text, record) => (
        <Space size='small'>
          <Button
            type='primary'
            size='small'
            shape='circle'
            onClick={() => navigate(`/home/publish/${record.id}`)}
            icon={<EditOutlined />}
          />
          <Button
            type='danger'
            size='small'
            shape='circle'
            onClick={() => del(record.id)}
            icon={<DeleteOutlined />}
          />
        </Space>
      )
    }
  ]

  return (
    <Card
      title={
        <Breadcrumb>
          <Breadcrumb.Item>
            <Link to='/home'>首页</Link>
          </Breadcrumb.Item>
          <Breadcrumb.Item>内容管理</Breadcrumb.Item>
        </Breadcrumb>
      }
      style={{ marginBottom: 20 }}
    >
      <Form name='basic'>
        <Form.Item label='状态' name='username'>
          <Radio.Group
            value={status}
            onChange={e => {
              query.status = e.target.value
              setStatus(e.target.value)
            }}
          >
            {STATUS.map(item => (
              <Radio value={item.id} key={item.id}>
                {item.title}
              </Radio>
            ))}
          </Radio.Group>
        </Form.Item>

        <Form.Item label='频道'>
          <Select
            onChange={channel_id => {
              query.channel_id = channel_id
              setChannel(channel_id)
            }}
            placeholder='请选择文章频道'
            style={{ width: 200 }}
            value={channel}
          >
            {channels.map(item => {
              return (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              )
            })}
          </Select>
        </Form.Item>

        <Form.Item label='日期'>
          <RangePicker
            locale={locale}
            value={date}
            onChange={(date, dateStrings) => {
              if (dateStrings && dateStrings.length === 2) {
                query.begin_pubdate = dateStrings[0]
                query.end_pubdate = dateStrings[1]

                setDate(date)
              }
            }}
          />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button
              type='primary'
              htmlType='submit'
              onClick={() => setQuery({ ...query })}
            >
              筛选
            </Button>
            <Button
              type='primary'
              htmlType='submit'
              onClick={() => {
                // 清空内容
                setStatus(null)
                setChannel(null)
                setDate(null)
                // 开始搜索
                setQuery({
                  status: null,
                  channel_id: null,
                  begin_pubdate: null,
                  end_pubdate: null,
                  page: 1,
                  per_page: 10
                })
              }}
            >
              清除
            </Button>
          </Space>
        </Form.Item>
      </Form>
      {/* 表格 */}
      <Table
        columns={columns}
        dataSource={list}
        rowKey='id'
        bordered
        title={() => `根据筛选条件共查询到 ${total_count} 条结果：`}
        pagination={{
          position: ['bottomCenter'],
          pageSize: query.per_page,
          total: total_count,
          onChange: (page, pageSize) => {
            // 当页码或是页容量改变了
            // console.log(page, pageSize)
            setQuery({
              ...query,
              page,
              per_page: pageSize
            })
          }
        }}
      />
    </Card>
  )
}

export default Article
